<template>
  <el-dialog :title="$t('table.add')" width="700px" :visible="true" @close="onClose">
    <el-row>
      <el-col :span="12">
        <el-form :model="form" :rules="rules" ref="dialog-form" label-width="70px" size="small">
          <el-form-item :label="$t('role.name')" prop="name">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item :label="$t('role.group')" prop="group" v-if="groups.length!=1">
            <el-select v-model="form.group" value-key="id" clearable placeholder="请选择" style="width: 100%;" @change="onGroupChange">
              <el-option v-for="item in groups" :key="item.id" :label="item.name" :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('role.group')" v-else>
            <el-input :value="form.group.name" readonly></el-input>
          </el-form-item>
          <el-form-item :label="$t('role.org')" prop="org" v-if="orgs.length!=1">
            <el-select v-model="form.org" value-key="id" clearable placeholder="请选择" style="width: 100%;">
              <el-option v-for="item in orgs" :key="item.id" :label="item.name" :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('role.org')" v-else>
            <el-input :value="form.org.name" readonly></el-input>
          </el-form-item>
          <el-form-item :label="$t('role.authorities')" prop="authorities">
            <div class="el-input__inner el-input--small" style="min-height: 32px; height: auto;">
              <el-tag type="small" v-for="(authority, index) in form.authorities" :key="authority.id" closable @close="onTagClose(index)" style="margin-left: 5px;">{{authority.name}}</el-tag>
            </div>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="12">
        <el-form :model="query" :inline="true" ref="searchForm">
          <el-form-item>
            <el-input v-model="query.name" :placeholder="$t('role.authorityName')" clearable maxlength="30"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" icon="el-icon-search" @click="reloadAuthorities">{{$t('table.search')}}</el-button>
          </el-form-item>
        </el-form>
        <div style="padding-left: 20px;">
          <el-table ref="table" :data="authoritiesData" size="mini" border highlight-current-row  style="width: 100%;" height="400">
            <el-table-column prop="name" :label="$t('authority.name')"></el-table-column>
            <!--<el-table-column prop="code" :label="$t('authority.code')"></el-table-column>-->
            <el-table-column :label="$t('table.opt')" width="80">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="addAuthority(scope.row)">{{$t('table.add')}}</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
    </el-row>
    <div slot="footer" class="dialog-footer">
      <el-button @click="onClose">{{$t('dialog.cancel')}}</el-button>
      <el-button type="primary" @click="save">{{$t('dialog.save')}}</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import Vue from 'vue'
  import { vsprintf } from 'sprintf-js/dist/sprintf.min.js'
  import { validExists, saveToSubmit } from '@/utils/utils'
  import { fetchQuery } from '@/api/restful'

  export default {
    data() {
      const validName = (rule, value, callback) => {
        if(this.form.group && this.form.org){
          validExists.apply(this, [value, callback, {groupId: this.form.group.id, orgId: this.form.org.id, name: value}]);
        }
      };
      return {
        form: {
          authorities:[]
        },
        rules:{
          name:[
            { required: true, message:this.$t('rules.message.required'), trigger: 'blur' },
            { max: 20, message: vsprintf(this.$t('rules.message.maxLen'), 20), trigger: 'blur' },
            { validator: validName, trigger: 'blur' }
          ],
          group:[
            { required: true, message:this.$t('rules.message.required'), trigger: 'blur' }
          ],
          org:[
            { required: true, message:this.$t('rules.message.required'), trigger: 'blur' }
          ],
          authorities:[
            { required: true, message:this.$t('rules.message.required'), trigger: 'blur' },
          ]
        },
        authoritiesData:[],
        query:{},
        groups:[],
        orgs:[]
      };
    },
    methods: {
      save(){
        saveToSubmit.apply(this, [this.form])
      },
      onClose(){
        this.$router.push("/");
      },
      onGroupChange(){
        if(this.form.group){
          this.query.groupId =  this.form.group.id;
          this.reloadAuthorities();
        }
        else{
          this.authoritiesData.splice(0, this.authoritiesData.length);
        }
        if(this.form.authorities.length>0){
          this.form.authorities.splice(0, this.form.authorities.length);
        }
      },
      addAuthority(row){
        for(var i=0; i<this.form.authorities.length; i++){
          var authority = this.form.authorities[i];
          if(authority.id == row.id){
            this.$message({
              message: this.$t('role.authorityExists'),
              type: 'warning'
            });
            return;
          }
        }
        Vue.set(this.form.authorities, this.form.authorities.length, row);
      },
      onTagClose(index){
        this.form.authorities.splice(index, 1);
      },
      reloadAuthorities(){
        fetchQuery('/authority/query', this.query).then(response => {
          if(response.data.success) {
            this.authoritiesData.splice(0, this.authoritiesData.length);
            for(var i=0; i<response.data.result.length; i++) {
              Vue.set(this.authoritiesData, i, response.data.result[i]);
            }
          }
        })
      }
    },
    mounted: function(){
      /**自动授权用户组不能创建角色，query:{'autoAuth': false}*/
      fetchQuery('/userGroup/queryByUser',{'autoAuth': false}).then( response => {
        if(response.data.success){
          for(var i=0; i<response.data.result.length; i++) {
            Vue.set(this.groups, i, response.data.result[i]);
          }
          if(response.data.result.length==1){
            this.form.group = response.data.result[0];
            this.query.groupId =  this.form.group.id;
            this.reloadAuthorities();
          }
        }
      });
      fetchQuery('/org/queryByUser', {'authCode': 'ROLE'}).then( response => {
        if(response.data.success){
          for(var i=0; i<response.data.result.length; i++) {
            Vue.set(this.orgs, i, response.data.result[i]);
          }
          if(response.data.result.length==1){
            this.form.org = response.data.result[0];
          }
        }
      });
    }
  };
</script>
